<?php
namespace app\api\controller;
use app\common\lib\exception\ApiException;
use think\Exception;
use app\common\lib\db;
#use think\Db;

class User extends Base
{
    /**
     * 请求当前登录用户的所有信息
     * @return array user_msg
     */
    public function index()
    {
        if(request()->isPOST()) {
            $data = input('param.');
            $user_msg = $this->is_user($data);
            return show('200','ok',$user_msg);

        }
        throw new ApiException('非法请求',500);
    }

    /**
     * 个人中心首页展示基本信息
     * @return $data $user_msg
     */
    public function user_index()
    {
        if(request()->isPOST()) {
            $data = input('param.');
            $user_msg = $this->is_user($data);
            $info = $this->select_user_msg($user_msg);
            return show('200','ok',$info);
        }
        throw new ApiException('非法请求',500);
    }


    /**
     * 首页个人中心 信息
     * @param object $user_msg 用户所有信息
     * @return array $info 筛选过后信息
     */
    public function select_user_msg($user_msg)
    {
        $info = [
            'user_id'   => $user_msg['user_id'],
            'username'  => $user_msg['user_username'],
            'face_img'  => $user_msg['user_image'],
            'is_vip'    => $user_msg['is_vip'],
            'phone' => $user_msg['user_phone'],
            'start_time' => $user_msg['start_time'],
            'end_time' => $user_msg['end_time'],
        ];
        return $info;
    }

    public function base_user_index()
    {
        if(request()->isPOST()) {
            $data = input('param.');
            $user_msg = $this->is_user($data);
            #halt($user_msg);
            $info = $this->base_user_msg($user_msg);
            return show('200','ok',$info);
        }
        throw new ApiException('非法请求',500);
    }

    /**
     * 首页个人中心 基本信息
     * @param object $user_msg 用户所有信息
     * @return array $info 筛选过后信息
     */
    public function base_user_msg($user_msg)
    {
        $data = $this->select_user_msg($user_msg);
        $data['nickname'] = $user_msg['user_nickname'];
        $data['birth'] = $user_msg['user_birthday'];
        $data['address'] =  db\DbCommon::area($user_msg['user_sheng'],$user_msg['user_shi'],$user_msg['user_qu']);
        return $data;
    }

    /**
     * 用户基本信息修改
     * @return array $update_msg
     */
    public function edit_base_user()
    {
        /**
         * 传过来的数据一定要包含`user_id`
         */
        if(request()->isPOST()) {
            $data = input('param.');
            $this->is_user($data);  //判断基本传参是否合法
            $data ['update_time'] = date('Y-m-d H:i:s');

            try{
                $res = $this->_user->allowField(true)->save($data,['user_id'=>$data['user_id']]);
            }catch (\Exception $e) {
                throw new ApiException($e->getMessage(),'500');
            }
            if(!$res) {
                return show('200','没有做任何更改');
            }
            return show('200','更新成功',$data);
        }
        throw new ApiException('非法请求',500);
    }



    /**
     * 封装用户查询模块
     * 以数组形式传递 user_id
     * @param array $data $data['user_id']
     * @return array $user_msg
     */
    public function is_user($data)
    {
        $is_array = check_array($data); //基本判断请求是否合法
        if(!$is_array || !isset($data['user_id'])) {
            throw new ApiException('数据请求不合法','500');
        }
        try{
            $user_msg = $this->get_this_user_msg($data['user_id']);
        }catch (\Exception $e){
            throw new ApiException($e->getMessage(),'500');
        }
        if(!$user_msg) {
            throw new ApiException('查询不到该用户','200');
        }elseif ($user_msg['user_status'] != 1){
            return show('500','登录请求被拒绝，原因 '.get_user_status($user_msg['user_status']));
        }
        return $user_msg;
    }

    /**
     * 通用查询用户基本信息
     * @param number $uid
     * @return array $user_msg
     */
    public function get_this_user_msg($uid)
    {
        $data = $this->_user->get_user_msg($uid);
        return $data;
    }


    /**
     * @param int is_collect 1 取消收藏 2 添加收藏
     * @param number f_id    资源 id music_id/video_id
     * @param number user_id 当前登录用户id
     * @param number is_type 当前资源收藏的类别
     * @return bool 取消收藏
     */
    public function is_collect_like()
    {
        if(\request()->isPOST()) {
            $like_data = input('param.');
            //halt($like_data);
            $this->is_user($like_data);
            $is_array = check_array($like_data); //基本判断请求是否合法
            if(!$is_array || !isset($like_data['f_id']) || empty($like_data['f_id']) ||!isset($like_data['is_type']) || empty($like_data['is_type'])||!isset($like_data['user_id']) || empty($like_data['user_id'])||!isset($like_data['is_collect']) || empty($like_data['is_collect'])) {
                throw new ApiException('数据请求不合法','500');
            }
            //取消收藏
            if($like_data['is_collect'] == 1) {
                $res = $this->_like->get(['f_id'=>$like_data['f_id'],'user_id'=>$like_data['user_id'],'is_type'=>$like_data['is_type']]);
                if(!$res) {
                    throw new ApiException('取消失败','200');
                }
                $data = [
                    'f_id'   =>$like_data['f_id'],
                    'user_id'=>$like_data['user_id'],
                    'is_type'=>$like_data['is_type']
                ];
//            halt($like_data);
                $ret = $this->_like->where($data)->delete();
                if(!$ret) {
                    throw new ApiException('数据库错误','200');
                }
                return show('200','已取消收藏');
            }elseif ($like_data['is_collect'] == 2) {
                $res = $this->_like->get(['f_id'=>$like_data['f_id'],'user_id'=>$like_data['user_id'],'is_type'=>$like_data['is_type']]);
                if($res) {
                    throw new ApiException(' 添加失败','200');
                }
                $data = [
                    'f_id'   =>$like_data['f_id'],
                    'user_id'=>$like_data['user_id'],
                    'is_type'=>$like_data['is_type']
                ];
                $ret = $this->_like->save($data);
                if(!$ret) {
                    throw new ApiException('数据库错误','200');
                }
                return show('200','已添加收藏');
            }else {
                throw new ApiException('非法参数','500');
            }
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * 获取当前资源url地址
     * @return string $url
     */
    public function user_like_link()
    {
        if(\request()->isPOST()) {
            $like_data = input('param.');
            //halt($like_data);
            $is_array = check_array($like_data); //基本判断请求是否合法
            if(!$is_array || !isset($like_data['id']) || empty($like_data['id']) ||!isset($like_data['is_type']) || empty($like_data['is_type'])) {
                throw new ApiException('数据请求不合法','500');
            }
            $data = db\DbCommon::get_media_url($like_data['id'],$like_data['is_type']);
            if(!$data) {
                throw new ApiException('当前资源找不到','404');
            }
            $info = [
                'url' => $data['0']['chirden_url'],
                'upload_time' => $data['0']['chirden_time']
            ];
            return show('200','ok',$info);
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * 接收参数：
     * @param number $uid 用户user_id
     * @param number $type 收藏类别 1 视频 2 音乐 默认是视频
     * @param number $page 页码数量 默认20条
     */
    public function get_user_likes($uid,$type = '1',$nowPage=1,$limits=10)
    {
        try{
            $data = $this->_like->get_user_like($uid, $type,$nowPage,$limits);
        }catch (\Exception $e){
            throw new ApiException($e->getMessage());
        }
        return $data;
    }

    /**
     * @param number $id 资源id
     * @param number $type 资源类别 1 视频 2 音乐
     * @return mixed|string
     */
    public function get_this_media_msg($id,$type)
    {
        $data = db\DbCommon::get_media_msg($id,$type);
        return $data;
    }

    /**
     * 收藏保留指定项目
     * @param $f_id
     * @param $is_type
     * @return array $data media_name media_img media_vip
     */
    public function get_only_media($f_id,$is_type)
    {
        $data = $this->get_this_media_msg($f_id,$is_type);
        if(isset($data['0']['video_f_id'])) {
            $info = [
                'video_id'  => $data['0']['video_id'],
                'video_name' => $data['0']['video_name'],
                'video_img' => $data['0']['video_img'],
                'person_id' => $data['0']['person_id'],
                'person_name' => $data['0']['person_name'],
                'person_img' => $data['0']['person_img'],
                'video_modular_name' => $data['0']['video_modular_name'],
//                'url'       => db\DbCommon::get_media_url($data['0']['video_id'],$is_type)[0],
                'url'       => $data['0']['music_url'],
                'is_vip' => $data['0']['is_vip'],
                'video_performer' => $data['0']['video_performer']
            ];
        }else {
            $info = [
                'music_id' => $data['0']['music_id'],
                'music_name' => $data['0']['music_name'],
                'music_img' => $data['0']['music_img'],
                'person_id' => $data['0']['person_id'],
                'person_name' => $data['0']['person_name'],
                'person_img' => $data['0']['person_img'],
                'music_modular_name' => $data['0']['video_modular_name'],
                'url'       =>  $data['0']['music_url'],
                'is_vip' => $data['0']['is_vip'],
                'music_performer' => $data['0']['music_performer']
            ];
        }
        return $info;
    }

    /**
     * 收藏保留指定项目
     * @param $f_id
     * @param $is_type
     * @return array $data media_name media_img media_vip
     */
    public function get_only_media_bak($children_id,$is_type)
    {
        $data = $this->get_this_media_msg($children_id,$is_type);
        $info = [
            'video_id'  => $data['0']['video_id'],
            'video_name' => $data['0']['video_name'],
            'video_img' => $data['0']['video_img'],
            'person_id' => $data['0']['person_id'],
            'person_name' => $data['0']['person_name'],
            'person_img' => $data['0']['person_img'],
            'video_modular_name' => $data['0']['video_modular_name'],
            'url'       => db\DbCommon::get_media_url($children_id,$is_type)[0],
            'is_vip' => $data['0']['is_vip'],
            'video_performer' => $data['0']['video_performer']
        ];
        return $info;
    }


    /**
     * post
     * 必存添加`user_id`字段
     * `opinion_name`反馈内容
     * @return array $data[]
     */
    public function opinion()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $this->is_user($data);  //判断基本传参是否合法
            if(!isset($data['opinion_name'])) {
                throw new ApiException('反馈内容不得为空','500');
            }
            $data['opinion_time'] = date('Y-m-d H:i:s'); //时间
            $data['opinion_uid']  = $data['user_id'];
//            halt($data);
            try{
                $res = $this->_opinion->save_allow($data);
            }catch (\Exception $e){
                throw new ApiException($e->getMessage(),'500');
            }
            if(!$res) {
                throw new ApiException('数据库操作失败','500');
            }
            unset($data['user_id']);
            return show('200','反馈成功',$data);
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * post/get 无传参要求
     * @return array $msg 问题列表
     */
    public function question_list()
    {
        $data = db\DbCommon::question_list();
        $type = $this->_question_type->select();
        $type_len = count($type);
        $list_len = count($data);
        $data = array();
        for ($i = 0;$i < $type_len;$i ++) {
            $type[$i]['item'] = $this->get_question_item($type[$i]['type_id']);
            unset($type[$i]['set_time'],$type[$i]['item']['content']);
        }
        return show('200','ok',$type);
    }

    public function question_list_bak()
    {
        $data = db\DbCommon::question_list();
        $type_name = $this->_question_type->column('name');
        $type_id = $this->_question_type->column('type_id');
//        halt($type);
        $type_len = count($type_name);
        $list_len = count($data);

        $msg = return_question($data,$type_name);
        $data = array();
        for ($i = 0;$i < $type_len;$i ++) {
            $data[$i][$type_name[$i]] = $this->get_question_item($type_id[$i]);
        }
        return show('200','ok',$data);
    }

    public function get_question_item($type_id)
    {
        $data = $this->_question->where(['type'=>$type_id])->select();
        return $data;
    }

    /**
     * 一定要存在问题列表`id`
     */
    public function question_con()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $is_array = check_array($data); //基本判断请求是否合法
            if(!$is_array) {
                throw new ApiException('数据请求不合法','500');
            }
//            halt($data);
            $ret = $this->_question->get(['id'=>$data['id']]);
            if(!$ret) {
                throw new ApiException('数据库错误','500');
            }
            unset($ret['type']);
            return show('200','ok',$ret);
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * post请求用户浏览历史
     * 数据表设计有问题，暂缓
     */
    public function user_history()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $is_array = check_array($data); //基本判断请求是否合法
            if(!$is_array ) {
                throw new ApiException('数据请求不合法','500');
            }
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * @return array $data 我的关注
     */
    public function user_attention()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $is_array = check_array($data); //基本判断请求是否合法
            $this->is_user($data);  //判断当前用户是否合法
            if(!$is_array) {
                throw new ApiException('数据请求不合法','500');
            }
            $is_page = $this->is_page($data);
            if(!$is_page) {
                throw new ApiException('请传入页码信息','200');
            }
            try{
                //key value nowPage limits
                $res = Model('Attention')->get_page_msg('att_uid',$data['user_id']);
            }catch (\Exception $e) {
                throw new ApiException($e->getMessage(),'200');
            }
            if(!count($res)) {
                return show('200','当前用户没有关注任何名家');
            }
            $att_count = Model('Attention')->count_all_num();
            if($data['limits'] > $att_count && $data['nowPage'] > 1) {
                throw new ApiException('没有更多了','200');
            }
            foreach ($res as $key => $value) {
                $ret = $this->get_person($value['att_person_id']);
                $value['item'] = $ret;
                unset($ret['person_id']);
            }
//            die;
            return show('200','ok',$res);
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * @param array $data
     * @return bool 是否传入页码？
     */
    public function is_page($data)
    {
        $is_array = check_array($data); //基本判断请求是否合法
        if(!$is_array ) {
            return false;
        }
        if(!isset($data['nowPage']) || !isset($data['limits']) || empty($data['nowPage'])||empty($data['limits'])) {
            return false;
        }
        return true;
    }

    /**
     * @param number $person_id
     * @return array $ret
     */
    public function get_person($person_id)
    {
        $ret = Model('Person')->get(['person_id'=>$person_id]);
        unset($ret['is_index'],$ret['person_time']);
        return $ret;
    }

    /**
     * @param int person_id 名家id
     * @return array $data 指定名家msg
     */
    public function person_info()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $is_array = check_array($data); //基本判断请求是否合法
            if(!$is_array || !isset($data['person_id']) || empty($data['person_id'])) {
                throw new ApiException('请传入名家id','500');
            }
            $person_info = $this->get_person($data['person_id']);
            if(!$person_info) {
                throw new ApiException('找不到该名家','200');
            }
            return show('200','ok',$person_info);
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * 添加／取消关注
     * @param int $type 1关注 2取消关注
     * @param number $user_id
     * @param number $person_id
     * @throws ApiException
     */
    public function select_att()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $is_array = check_array($data); //基本判断请求是否合法
            if(!$is_array || !isset($data['att_person_id']) || empty($data['att_person_id'])|| !isset($data['att_uid']) || empty($data['att_uid'])|| !isset($data['type']) || empty($data['type'])) {
                throw new ApiException('缺少参数','500');
            }
            if($data['type'] == 2) {    //关注
                $ret = $this->is_attention($data['att_uid'],$data['att_person_id']);
                if($ret) {
                    throw new ApiException('当前已关注，无需重复关注','200');
                }
                $data['att_time'] = date('Y-m-d H:i:s');
                try{
                    $res = Model('Attention')->save_allow($data);
                }catch (\Exception $e) {
                    throw new ApiException($e->getMessage(),'500');
                }
                if(!$res) {
                    throw new ApiException('数据库错误','500');
                }
                return show('200','成功关注');
            }elseif($data['type'] == 1) {   //取消关注
                $ret = $this->is_attention($data['att_uid'],$data['att_person_id']);
                if(!$ret) {
                    throw new ApiException('当前已取消关注，无需重复取消','200');
                }
                try{
                    $res = Model('Attention')->where(['att_uid'=>$data['att_uid'],'att_person_id'=>$data['att_person_id']])->delete();
                }catch (\Exception $e) {
                    throw new ApiException($e->getMessage(),'500');
                }
                if(!$res) {
                    throw new ApiException('数据库错误','500');
                }
                return show('200','成功取消关注');
            }else{  //参数错误
                throw new ApiException('参数错误','500');
            }
        }
        throw new ApiException('非法请求','500');
    }

    /**
     * 当前用户是否存在关注指定用户
     * @param number $att_uid
     * @param number $att_person_id
     * @return bool
     */
    public function is_attention($user_id,$person_id)
    {
        if(!isset($user_id) || !isset($person_id)) {
            throw new ApiException('缺少参数','500');
        }
        $res = Model('Attention')->get(['att_uid'=>$user_id,'att_person_id'=>$person_id]);
        if(!$res) {
            return false;
        }
        return true;
    }
    /**
     * 视频覆盖
     * @param $user_id
     * @param $media_type
     * @param $media_id
     * @return bool 查询是否已存在历史，覆盖重新写入
     */
    public function is_video_history($user_id,$media_type,$media_id,$children_id) {
        $res = $this->_history->get(['user_id'=>$user_id,'media_type'=>$media_type,'media_id'=>$media_id,'children_id'=>$children_id]);
        if(!$res) {
            return false;
        }
        return $res;
    }

    /*
     * 访问历史记录 视频
     * @param number user_id
     * @param int media_type 1 video 2 music
     * @param number limits
     * @param number nowPage
     * return bool
     */
    public function history_video_list()
    {
        if(\request()->isPOST()) {
            $data = input('param.');
            $is_array = check_array($data); //基本判断请求是否合法
            $this->is_user($data);
            if(!$is_array || !isset($data['user_id']) || empty($data['user_id'])|| !isset($data['media_type']) || $data['media_type'] != 1) {
                throw new ApiException('传参不合法或缺少参数','500');
            }
            if(!isset($data['nowPage']) || !isset($data['limits'])) {
                throw new ApiException('请传入页码信息','500');
            }
            $history_count = $this->_history->type_count_media($data['user_id'],$data['media_type']);
            if($data['limits'] > $history_count && $data['nowPage'] > 1) {
                throw new ApiException('没有更多了','200');
            }
            try{
                $media_data = $this->_history->type_select_media($data['user_id'],$data['media_type'],$data['nowPage'],$data['limits']);
            }catch (\Exception $e) {
                throw new ApiException($e->getMessage(),'200');
            }
            if(!count($media_data)) {   //判断是否为空
                return show('200','该用户当前类别为空');
            }
            //return show('200','ok',$media_data);
            foreach ($media_data as $key => $value) {
                $is_like = $this->is_like($value['user_id'],$value['media_type'],$value['media_id']);
                if(!$is_like) {
                    $value['is_like'] = '2';
                }else {
                    $value['is_like'] = '1';
                }
                $value['video_modular_name'] = $this->video_modular_name($value['media_id'],1);
                $data = $this->get_video_children($value['media_id'],$value['children_id']);
//                $data = $this->get_only_media_bak($value['children_id'],$value['media_type']);;
                $value['item'] = $data;
            }
            return show('200','ok',$media_data);
        }
        throw new ApiException('非法请求','500');
    }

    public function get_video_children($video_id,$children_id)
    {
        return db\DbCommon::get_video_children($video_id,$children_id);
    }

    public function is_like($user_id,$is_type,$f_id)
    {
        $is_like = $this->_like->get(['user_id'=>$user_id,'is_type'=>$is_type,'f_id'=>$f_id]);
        if(!$is_like) {
            return false;
        }
        return true;
    }

    public function video_modular_name($video_id,$type=1)
    {
        $data = db\DbCommon::get_media_msg($video_id,$type);
        return $data['0']['video_modular_name'];
    }
}